package db

import (
	"gdfs-service/conf"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
)

var db *gorm.DB
var err error

/**
 *   gorm v2 版本初始化数据库
 */
func InitDB(dbConfig *conf.Config) {
	log.Println("数据库初始化")
	dsn := dbConfig.GetEnvValue("gorm.username") + ":" + dbConfig.GetEnvValue("gorm.password") + "@tcp(" + dbConfig.GetEnvValue("gorm.address") + ")/" + dbConfig.GetEnvValue("gorm.dbname") + "?charset=utf8&parseTime=True&loc=Local"
	log.Println(dsn)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{SingularTable: true}, //是否采用负数表名
		Logger:         logger.Default.LogMode(logger.Info),        //打印日志级别
	})
	if err != nil {
		log.Println(err)
		panic(err)
	}

}

//运行服务器模式建表SQL
func RunServerDB() {
	// 迁移表
	db.AutoMigrate(&FileInfo{}, &StoreInfo{})
	//建立索引
	db.Migrator().CreateIndex(&FileInfo{}, "file_key")

}

//同步分页查询
func PageSyncQuery(scopes []func(*gorm.DB) *gorm.DB, pageSize, pageNo int, order string) *gorm.DB {
	return db.Scopes(scopes...).Limit(pageSize).Offset((pageNo - 1) * pageSize).Order(order)
}

//分页查询
func PageQuery(scopes []func(*gorm.DB) *gorm.DB, pageSize, pageNo int, order string) *gorm.DB {
	//return db.Scopes(scopes...).Limit(pageSize).Offset((pageNo - 1) * pageSize).Order(order)
	scopes = append(scopes, Paginate(pageSize, pageNo))
	return db.Scopes(scopes...).Order(order)
}

//获取分页总数
func GetPageQueryTotal(scopes []func(*gorm.DB) *gorm.DB) *gorm.DB {
	return db.Scopes(scopes...)
}

func Paginate(pageSize, pageNo int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if pageNo == 0 {
			pageNo = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (pageNo - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func GetDB() *gorm.DB {
	return db
}
